package com.example.mallapi.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.mallapi.entity.Product;
import com.example.mallapi.entity.Productimage;
import com.example.mallapi.entity.Property;
import com.example.mallapi.entity.Propertyvalue;
import com.example.mallapi.mapper.ProductMapper;
import com.example.mallapi.mapper.ProductimageMapper;
import com.example.mallapi.mapper.PropertyMapper;
import com.example.mallapi.mapper.PropertyvalueMapper;
import com.example.mallapi.qo.ProductQo;
import com.example.mallapi.service.IProductService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.PropertyValue;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.security.auth.callback.LanguageCallback;
import java.io.File;
import java.io.IOException;
import java.io.Serializable;
import java.time.LocalDateTime;
import java.util.List;
import java.util.UUID;

/**
 * <p>
 * 产品表 服务实现类
 * </p>
 *
 * @author zhengpf
 * @since 2023-06-03
 */
@Service
@Transactional
public class ProductServiceImpl extends ServiceImpl<ProductMapper, Product> implements IProductService {

    @Value("${upload.path}")
    private String uploadPath;

    @Autowired
    private ProductimageMapper productimageMapper;

    @Autowired
    private PropertyvalueMapper propertyvalueMapper;

    @Autowired
    private PropertyMapper propertyMapper;

    @Override
    public IPage<Product> page(ProductQo qo) {
        LambdaQueryWrapper<Product> wrapper = new LambdaQueryWrapper<>();
        //条件直接默认为 &&
        //-1 默认不区分  是否上架 商品分类
        wrapper
        .like(StringUtils.isNotBlank(qo.getProductName()),Product::getProductName,qo.getProductName())
        .eq(qo.getCategoryId() != -1,Product::getProductCategoryId,qo.getCategoryId())
        .eq(qo.getIsUp() != -1,Product::getProductIsUp,qo.getIsUp())
        .ge(qo.getMinPrice() != null,Product::getProductSalePrice,qo.getMinPrice())
        .le(qo.getMaxPrice() != null,Product::getProductSalePrice,qo.getMaxPrice());

        IPage<Product> page = new Page(qo.getPageNum(),qo.getPageSize());

        page = baseMapper.selectPage(page, wrapper);
        return page;
    }

    @Override
    public String uploads(MultipartFile file, String imageType) {
        //为上传的文件重起名字  名字+后缀名
        String filename = file.getOriginalFilename();
        //后缀
        String ext = filename.substring(filename.lastIndexOf("."));

        String newFileName = UUID.randomUUID() + ext;

        //上传文件：保持到某个位置
        String filePath = uploadPath + imageType;

        //校验路径是否存在
        File fileUpLoadPath = new File(filePath);
        if(!fileUpLoadPath.exists()){
            //创建目录
//            fileUpLoadPath.mkdir();//创建一层目录
            fileUpLoadPath.mkdirs();//创建多层目录
        }

        try{
            //将文件传递到指定路径
            file.transferTo(new File(fileUpLoadPath + "/" + newFileName));  //do
            return "img_mall/" +imageType + "/" + newFileName;
        }catch (IOException e){
            e.printStackTrace();
        }
        return null;
    }


    @Override
    public boolean save(Product entity) {
        //保存商品信息
        //设置创建时间
        entity.setProductCreateDate(LocalDateTime.now());
        baseMapper.insert(entity);

        //保存商品的图片信息
        //保存概述图片
        List<Productimage> singlePic = entity.getSinglePic();
        if(singlePic != null && singlePic.size() > 0){
            for(Productimage p: singlePic){
         //    为Productimage设置商品id
                p.setProductimageProductId(entity.getProductId());
                productimageMapper.insert(p);
            }
        }

        //保存详情图片
        List<Productimage> detailPic = entity.getDetailPic();
        if(detailPic != null && detailPic.size() > 0){
            for(Productimage p: detailPic){
                //    为Productimage设置商品id
                p.setProductimageProductId(entity.getProductId());
                productimageMapper.insert(p);
            }
        }
        //保存属性值信息
        List<Propertyvalue> list = entity.getPropvalues();
        if(list != null && list.size() > 0){
            for (Propertyvalue propertyvalue : list) {
                //只需保存属性值表的产品di
                //属性id为 entity中前端自动注入
                propertyvalue.setPropertyvalueProductId(entity.getProductId());
                propertyvalueMapper.insert(propertyvalue);
            }
        }
        return super.save(entity);
    }


    @Override
    public Product getById(Integer id) {
        //查询商品名 等信息
        Product product = baseMapper.selectById(id);

        //查询商品概述图片
        LambdaQueryWrapper<Productimage> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Productimage::getProductimageProductId,id);
        //指定查询详细图
        queryWrapper.eq(Productimage::getProductimageType,0);
        List<Productimage> productimage1 = productimageMapper.selectList(queryWrapper);


        //查询商品详细图片
        LambdaQueryWrapper<Productimage> queryWrapper2 = new LambdaQueryWrapper<>();
        queryWrapper2.eq(Productimage::getProductimageProductId,id);
        //指定查询详细图
        queryWrapper.eq(Productimage::getProductimageType,1);
        List<Productimage> productimages2 = productimageMapper.selectList(queryWrapper);


        //查询商品的属性值信息
        LambdaQueryWrapper<Propertyvalue> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Propertyvalue::getPropertyvalueProductId,id);
        List<Propertyvalue> propertyvalue = propertyvalueMapper.selectList(wrapper);

        //查询属性名
        //遍历出每一个属性值，分别查询属性值对应的属性名------------------------------优化：写俩边表的sql查询
        if(propertyvalue != null && propertyvalue.size() > 0){
            for (Propertyvalue p : propertyvalue) {
                Property property = propertyMapper.selectById(p.getPropertyvaluePropertyId());
                p.setPropertyName(property.getPropertyName());
            }
        }

        product.setSinglePic(productimage1);
        product.setDetailPic(productimages2);
        product.setPropvalues(propertyvalue);

        return product;
    }

    @Override
    public boolean updateById(Product entity) {

        //修改商品信息
        baseMapper.updateById(entity);

        //修改概述图片
        LambdaUpdateWrapper<Productimage> wrapper = new LambdaUpdateWrapper<>();
        wrapper.eq(Productimage::getProductimageProductId,entity.getProductId());
        productimageMapper.delete(wrapper);

        List<Productimage> singlePic = entity.getSinglePic();
        if(singlePic != null && singlePic.size() > 0){
            for (Productimage p : singlePic) {
                p.setProductimageProductId(entity.getProductId());
                productimageMapper.insert(p);
            }
        }


        //修改详细图

        List<Productimage> detailPic = entity.getDetailPic();
        if(detailPic != null && detailPic.size() > 0){
            for (Productimage p : detailPic) {
                p.setProductimageProductId(entity.getProductId());
                productimageMapper.insert(p);
            }
        }


        //修改属性值
        //删除商品原有的属性值信息
        LambdaUpdateWrapper<Propertyvalue> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.eq(Propertyvalue::getPropertyvalueProductId,entity.getProductId());
        propertyvalueMapper.delete(updateWrapper);

        List<Propertyvalue> list = entity.getPropvalues();
        if(list != null && list.size() > 0){
            for (Propertyvalue propertyvalue : list) {
                propertyvalue.setPropertyvalueProductId(entity.getProductId());
                propertyvalueMapper.insert(propertyvalue);
            }
        }
        return false;
    }

    @Override
    public boolean removeById(Serializable id) {
        //删除商品表信息
        baseMapper.deleteById(id);

        //删除属性值信息
        LambdaUpdateWrapper<Propertyvalue> wrapper1 = new LambdaUpdateWrapper<>();
        wrapper1.eq(Propertyvalue::getPropertyvalueProductId,id);
        propertyvalueMapper.delete(wrapper1);

        //删除商品图片信息
        LambdaUpdateWrapper<Productimage> wrapper2 = new LambdaUpdateWrapper<>();
        wrapper2.eq(Productimage::getProductimageProductId,id);
        productimageMapper.delete(wrapper2);

        return false;
    }
}
